<template>
  <a-modal :visible="visible" width="45%" title="审批配置" cancel-text="关闭" unmount-on-close :mask-closable="false" @cancel="close">
    <a-spin v-if="loading" tip="加载中..." />
    <SettingForm v-else ref="formRef" :settings="settingsDetail" />

    <!-- 底部 -->
    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button type="primary" @click="onSubmit" :loading="okLoading">确认</a-button>
    </template>
  </a-modal>
</template>

<script setup>
  import { ref } from 'vue'
  import { getApprovalSetings, updateApprovalSetings } from '@/api/system/approvalSetings'
  import { Message } from '@arco-design/web-vue'
  import SettingForm from './components/setting-form.vue'

  const visible = ref(false)
  const close = () => {
    visible.value = false
  }
  const open = () => {
    visible.value = true
    getDetail()
  }
  const emits = defineEmits(['getApprovalSet'])

  // 详情
  const loading = ref(false)
  const settingsDetail = ref({})
  const getDetail = () => {
    loading.value = true
    getApprovalSetings({ type: 1 })
      .then((res) => {
        if (res.code == 200) {
          // 默认无填充1个空值
          let flowList = res.result.flowList || []
          flowList.forEach((item) => {
            item.post = +item.post
          })
          if (flowList.length == 0) {
            flowList = [{ id: undefined, post: undefined }]
          }
          settingsDetail.value = {
            type: 1,
            flowList: flowList,
            ifOpen: res.result.ifOpen,
          }
        }
      })
      .finally(() => {
        loading.value = false
      })
  }

  // 保存
  const formRef = ref()
  const okLoading = ref(false)
  const onSubmit = () => {
    const form = formRef.value.form
    // 检验数据
    if (form.ifOpen == 1) {
      for (let index = 0; index < form.flowList.length; index++) {
        const element = form.flowList[index]
        if (!element.post) {
          Message.error('请选择审批人岗位')
          return
        }
      }
    } else {
      form.flowList = form.flowList.filter((item) => item.post)
    }
    // type默认1 支出单审批
    updateApprovalSetings({ ...form, type: 1 }).then((res) => {
      okLoading.value = false
      if (res.code == 200) {
        Message.success('保存成功')
        close()
        emits('getApprovalSet')
      }
    })
  }

  defineExpose({
    open,
  })
</script>

<style scoped lang="less">
  .page-header {
    height: 32px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    .page-title {
      font-size: 16px;
      font-weight: bold;
      color: #1d2129;
    }
  }
  .content {
    width: 100%;
    margin-bottom: 40px;
  }
</style>
